
const express = require('express');
const router = express.Router();
const { asyncHandler } = require("../getSendResult");

const { default: Client, ...$sts } = require("@alicloud/sts20150401");
const $OpenApi = require('@alicloud/openapi-client');
const crypto = require('crypto');

const { accessKeyId, accessKeySecret, endpoint, bucket, roleArn } = require('../../config/ossConfig.js')

let config = new $OpenApi.Config({
  accessKeyId,
  accessKeySecret,
});

// 访问的域名
config.endpoint = endpoint;
const client = new Client(config);

// 生成OSS表单上传签名所需参数
const generateUploadParams = (credentials) => {
  // 过期时间（UTC时间，格式：ISO8601）
  const expiration = new Date(Date.now() + 15 * 60 * 1000).toISOString(); // 15分钟有效期

  // 策略文档
  const policy = {
    expiration,
    conditions: [
      ["content-length-range", 0, 104857600], // 100MB限制
      ["eq", "$bucket", bucket],
      ["starts-with", "$key", "uploads/"] // 限制上传路径
    ]
  };

  const policyBase64 = Buffer.from(JSON.stringify(policy)).toString('base64');

  // 使用STS临时密钥生成签名
  const signature = crypto
    .createHmac('sha1', credentials.accessKeySecret)
    .update(policyBase64)
    .digest('base64');

  // 生成OSS endpoint域名
  const host = `https://${bucket}.${credentials.region}.aliyuncs.com`;

  return {
    accessKeyId: credentials.accessKeyId,
    policy: policyBase64,
    signature,
    host,
    region: credentials.region,
    xOssSecurityToken: credentials.stsToken,
    xOssDate: expiration.replace(/[-:]/g, '').split('.')[0] + 'Z', // 格式: 20231128T104940Z
    success_action_status: '200'
  };
};

const request = new $sts.AssumeRoleRequest({});

request.durationSeconds = 3600;

request.policy = JSON.stringify({

  Version: '1',
  Statement: [{
    Effect: 'Allow',
    Action: ['oss:PutObject'],
    Resource: [`acs:oss:*:*:${bucket}/*`],
  }],
});


request.roleArn = roleArn;

request.roleSessionName = `upload-${Date.now().toString(36).slice(-6)}`;

router.get('/', asyncHandler(async (req, res) => {
  const result = await client.assumeRole(request);

  const credentials = {
    accessKeyId: result.body.credentials.accessKeyId,
    accessKeySecret: result.body.credentials.accessKeySecret,
    stsToken: result.body.credentials.securityToken,
    region: 'oss-cn-chengdu'
  };

  const uploadParams = generateUploadParams(credentials);
  // console.log(uploadParams, 'uploadParams');
  return {
    data: {
      ...uploadParams,
      bucket,
      // 添加前端需要的路径生成参数
      uploadPathTemplate: `uploads/${new Date().toISOString().split('T')[0]}/${Date.now()}_${Math.random().toString(36).slice(2, 8)
        }`

    }
  }
}));

module.exports = router;